import axios from "axios";
import router from "../router";
import Vue from "vue";
// const instance = axios.create(requestConfig);

// 各环境BaseURL配置
const ENVIRONMENT = {
  local: "api",
};

// Axios 请求实例配置
const request = axios.create({
  baseURL: ENVIRONMENT.local,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

export default request;

// 请求拦截器
request.interceptors.request.use((config) => {
  config.headers["token"] = sessionStorage.getItem("token");
  return config;
});

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      // 拦截登录失效、无权限操作
      if (response.data.code === 501) {
        sessionStorage.removeItem("token");
        sessionStorage.removeItem("username");
        sessionStorage.removeItem("menu");
        Vue.prototype.$alert(response.data.message, {
          confirmButtonText: "确定",
          showClose: false,
          callback() {
            router.push("/login");
          },
        });
      }
      return response;
    } else {
      Promise.reject();
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);
